package order

import (
	"fmt"
	"net/http"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/shopspring/decimal"
	"gorm.io/gorm"
	"ttsx/server/common/global"
	"ttsx/server/model"
	"ttsx/server/utils"
)

const (
	CashPay     = 1
	WeChatPay   = 2
	AlipayPay   = 3
	BankCardPay = 4
	TransPrice  = 10 // 运费
)

func ToOrder(ctx *gin.Context) { // 订单的展示
	// 获取uid、name、isactive
	uid := ctx.GetInt("uid")
	Name := ctx.GetString("username")
	IsActive := ctx.GetBool("IsActive")

	// 根据uid查询默认地址
	var NewDefaultAddress model.Address
	global.App.DB.Where("user_id = ?", uid).Where("isdefault = ?", true).Find(&NewDefaultAddress)
	DefaultAddr := fmt.Sprintf("%s	( %s 收 ) %s", NewDefaultAddress.Addr, NewDefaultAddress.Receiver, NewDefaultAddress.Phone)

	// 获取sku_ids
	cartKey := fmt.Sprintf("cartKey_%d", uid)
	var GoodsList []map[string]interface{}

	sku_ids := ctx.Query("sku_ids")
	if sku_ids == "" {
		ctx.Redirect(http.StatusFound, "/ttsx/cart/select")
	}
	sku_id_list := strings.Split(sku_ids, ",")

	total_amount := 0
	total_goodsNum := 0

	for i, sku_id := range sku_id_list {
		// 根据sku_id查询goodsSKU表
		var NewGoodsSKU map[string]interface{}
		global.App.DB.Model(&model.GoodsSKU{}).
			Select("name", "price", "unite", "image").
			Where("id = ?", sku_id).
			Find(&NewGoodsSKU)
		global.App.Log.Sugar().Infof("uid: %d, NewGoodsSKU: %v", uid, NewGoodsSKU)

		// 根据uid 查询redis
		countStr, _ := global.App.RDB.HGet(ctx, cartKey, sku_id).Result()
		NewGoodsSKU["count"] = countStr
		NewGoodsSKU["index"] = i + 1

		// 计算小计
		var amount float64
		price := utils.StrToFloat64(NewGoodsSKU["price"].(string))
		count := utils.StrToFloat64(countStr)
		amount = price * float64(count)
		NewGoodsSKU["amount"] = amount                             // 小计
		total_amount = total_amount + int(amount)                  // 商品的总价
		total_goodsNum = total_goodsNum + utils.StrToInt(countStr) // 商品的总数量

		GoodsList = append(GoodsList, NewGoodsSKU)
	}

	total_price := total_amount + TransPrice
	global.App.Log.Sugar().Infof("uid: %d, total_price: %d, GoodsList: %v", uid, total_price, GoodsList)

	ctx.HTML(http.StatusOK, "order/place_order.html", map[string]interface{}{
		"Name":              Name,
		"IsActive":          IsActive,
		"NewDefaultAddress": NewDefaultAddress,
		"Sku_ids":           sku_ids,
		"DefaultAddr":       DefaultAddr,
		"GoodsList":         GoodsList,
		"TotalGoodsNum":     total_goodsNum,
		"TotalAmount":       total_amount,
		"TransPrice":        TransPrice,
		"TotalPrice":        total_price,
	})
}

func CreateOrder(ctx *gin.Context) { // 订单的创建
	// 从cookies中获取信息
	uid := ctx.GetInt("uid")

	// 获取前端数据
	sku_ids := ctx.PostForm("sku_ids")
	addr_id := ctx.PostForm("addr_id")
	pay_id := utils.StrToInt(ctx.PostForm("pay_type"))

	// 校验数据
	if ret := global.App.DB.Where("id = ?", addr_id).Find(&model.Address{}); ret.RowsAffected == 0 {
		ctx.JSON(http.StatusOK, map[string]interface{}{"code": 1, "errMsg": "收件地址不存在"})
	}

	if pay_id <= 0 || pay_id > 4 {
		ctx.JSON(http.StatusOK, map[string]interface{}{"code": 2, "errMsg": "支付方式不存在"})
	}

	// 构建数据表其他字段数据
	orderId := fmt.Sprintf("%s%d", time.Now().Format("20060102150405"), uid)
	cartKey := fmt.Sprintf("cartKey_%d", uid)

	var total_count int = 0
	var total_price float64 = 0

	// 遍历sku_ids,插入数据到order_goods表
	sku_id_list := strings.Split(sku_ids, ",")

	err := global.App.DB.Transaction(func(tx *gorm.DB) error {
		// 遍历 sku_ids
		for _, sku_id := range sku_id_list {
			var newGoods model.GoodsSKU
			if ret := tx.Where("id = ?", sku_id).Find(&newGoods); ret.Error != nil || ret.RowsAffected == 0 {
				return fmt.Errorf("商品库存不足")
			}
			global.App.Log.Sugar().Infof("uid: %d, newGoods: %v", uid, newGoods)

			// 查询redis中商品数量
			count, _ := global.App.RDB.HGet(ctx, cartKey, sku_id).Result()
			countInt := utils.StrToInt(count)

			// 验证库存
			if countInt > newGoods.Stock {
				return fmt.Errorf("商品库存不足")
			}

			// 更新goodsSKU 表中的库存
			if ret := tx.Where("id = ?", sku_id).Where("stock = ?", newGoods.Stock).Updates(&model.GoodsSKU{
				Stock: newGoods.Stock - countInt,
				Sales: newGoods.Sales + 1,
			}); ret.RowsAffected == 0 || ret.Error != nil {
				return fmt.Errorf("下单失败1")
			}
			global.App.Log.Sugar().Infof("uid: %d, 更新库存成功!", uid)

			// 向 order_goods 表中insert数据
			if ret := tx.Create(&model.OrderGoods{
				Count:        countInt,
				Price:        newGoods.Price,
				OrderInfo_Id: utils.StrToInt(orderId),
				GoodsSKU_Id:  utils.StrToInt(sku_id),
			}); ret.RowsAffected == 0 || ret.Error != nil {
				return fmt.Errorf("下单失败2")
			}
			global.App.Log.Sugar().Infof("uid: %d, 新增order_goods信息成功!", uid)

			// 计算 总数量 和 总价格
			total_count = total_count + countInt
			total_price = total_price + newGoods.Price.InexactFloat64()
		}

		// 向 order_info 表中insert数据
		if ret := tx.Create(&model.OrderInfo{
			OrderId:      utils.StrToInt(orderId),
			PayMethod:    pay_id,
			TotalCount:   total_count,
			TotalPrice:   decimal.NewFromFloat(total_price),
			TransitPrice: decimal.NewFromInt(TransPrice),
			OrderStatus:  1,
			User_Id:      uid,
		}); ret.RowsAffected == 0 || ret.Error != nil {
			return fmt.Errorf("创建用户订单失败")
		}
		global.App.Log.Sugar().Infof("uid: %d, 新增order_info信息成功!", uid)

		// 删除 redis 中的购物车数量
		count, err := global.App.RDB.HDel(ctx, cartKey, sku_id_list...).Result()
		if count == 0 || err != nil {
			return fmt.Errorf("删除用户购物车失败")
		}
		global.App.Log.Sugar().Infof("删除购物车信息:[uid: %d, cartKey: %s]", uid, cartKey)

		return nil
	})
	if err != nil {
		ctx.JSON(http.StatusOK, map[string]interface{}{"code": 3, "errMsg": err.Error()})
	}
	global.App.Log.Sugar().Infof("uid: %d 订单提交成功!", uid)

	ctx.JSON(http.StatusOK, map[string]interface{}{"code": 4, "Msg": "订单提交成功"})
}
